package com.heking.speech.xunfei;

import android.content.Context;

import com.heking.speech.core.SpeechDialogListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import androidx.annotation.Keep;

/**
 * 科大讯飞自带的语音识别窗口
 *
 * @Author 35574
 * @Date 2020/7/8
 * @Description
 */
@Keep
public class XunFeiSpeechDialogWrap {
    private RecognizerDialog mDialog;
    private SpeechDialogListener mListener;
    /**
     * 识别完成后自动关闭窗口
     */
    private boolean autoCancel=true;

    public XunFeiSpeechDialogWrap(Context context) {
        mDialog = new RecognizerDialog(context, new SpeechInitListener(context));
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
        //设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mDialog.setParameter(SpeechConstant.ASR_PTT, "1");
        // 设置语音前端点:静音超时时间，单位ms，即用户多长时间不说话则当做超时处理
        //取值范围{1000～10000}
        mDialog.setParameter(SpeechConstant.VAD_BOS, "2000");
        //设置语音后端点:后端点静音检测时间，单位ms，即用户停止说话多长时间内即认为不再输入，
        //自动停止录音，范围{0~10000}
        mDialog.setParameter(SpeechConstant.VAD_EOS, "1500");

    }

    /**
     * 识别监听
     * @param speechDialogListener
     */
    public void setListener(SpeechDialogListener speechDialogListener) {
        mListener=speechDialogListener;
        if(mListener!=null){
            mDialog.setListener(new RecognizerDialogListener() {
                @Override
                public void onResult(RecognizerResult recognizerResult, boolean b) {
                   if(autoCancel){
                       mDialog.cancel();
                   }
                    if(recognizerResult!=null){
                        mListener.onResult(ResultParser.parseResult(recognizerResult.getResultString()));
                    }else{
                        mListener.onError(new com.heking.speech.core.SpeechError(10000));
                    }
                }

                @Override
                public void onError(SpeechError speechError) {
                    if(autoCancel){
                        mDialog.cancel();
                    }
                    mListener.onError(new com.heking.speech.core.SpeechError(speechError.getErrorCode()));
                }
            });
        }else{
            mDialog.setListener(null);
        }
    }



    public void show() {
        mDialog.show();
    }

    /**
     * 识别完成后自动关闭窗口
     * @param autoCancel
     */
    public void setAutoCancel(boolean autoCancel) {
        this.autoCancel = autoCancel;
    }

    public boolean isShowing() {
        return mDialog.isShowing();
    }

}
